package com.shop.user.conf.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class StatelessAuthcFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        String authorization = req.getHeader("Authorization");
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        Map<String, String> model = new HashMap<>();
        if (authorization == null || authorization == "") {
            onNotLogin(response);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        JSONObject jsonObjec = new JSONObject();

        Subject subject = this.getSubject(request, response);
        subject.login(token);
        jsonObjec.put("token:", subject.getSession().getId());
        model.put("code", 401 + "");
        model.put("msg", "token : username--" + username + "--password--" + password);
        model.put("data", jsonObjec.toJSONString());
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.getWriter().write(JSON.toJSONString(model));
        return false;
    }

    //登录失败时默认返回401状态码
    private void onTokenError(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Map<String, Object> model = new HashMap<>();
        model.put("code", "" + 401);
        model.put("msg", "token error");
        model.put("data", "");
        httpResponse.getWriter().write(JSON.toJSONString(model));
    }

    //登录失败时默认返回401状态码
    private void onNotLogin(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Map<String, Object> model = new HashMap<>();
        model.put("code", "" + 200);
        model.put("msg", "not login");
        model.put("data", "");
        httpResponse.getWriter().write(JSON.toJSONString(model));
    }
}
